using MediatR;
using ProduceBasicData.Api.Application.Command.ProcessReport;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.Domain.ProductionManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.ProcessReport
{
    /// <summary>
    /// 获取工艺报工数量处理类
    /// </summary>
    public class GetCraftReportQuantityHandler : IRequestHandler<GetCraftReportQuantityCommand, ApiResult<CraftReportChartDto>>
    {
        private readonly IBaseRespository<Production_report> _productionReportRepository;
        private readonly IBaseRespository<CraftModel> _craftRepository;

        public GetCraftReportQuantityHandler(
            IBaseRespository<Production_report> productionReportRepository,
            IBaseRespository<CraftModel> craftRepository)
        {
            _productionReportRepository = productionReportRepository;
            _craftRepository = craftRepository;
        }

        public async Task<ApiResult<CraftReportChartDto>> Handle(GetCraftReportQuantityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<CraftReportChartDto> result = new ApiResult<CraftReportChartDto>();

            try
            {
                var chartData = new CraftReportChartDto();

                // 获取所有工艺
                var allCrafts = _craftRepository.GetAll()
                    .Where(x => !x.Isdel)
                    .ToList();

                // 获取生产报工数据
                var productionReports = _productionReportRepository.GetAll()
                    .Where(x => !x.Isdel);

                // 应用日期筛选
                if (request.StartDate.HasValue)
                {
                    productionReports = productionReports.Where(x => x.Production_time >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    productionReports = productionReports.Where(x => x.Production_time <= request.EndDate.Value);
                }

                // 应用工艺筛选
                if (request.CraftId.HasValue)
                {
                    // 这里需要根据实际的关联关系来筛选
                    // 假设Production_report中有CraftId字段，如果没有则需要通过其他方式关联
                    productionReports = productionReports.Where(x => x.Product_id == request.CraftId.Value);
                }

                // 应用报工状态筛选
                if (request.ReportStatus.HasValue)
                {
                    productionReports = productionReports.Where(x => x.Report_status == request.ReportStatus.Value);
                }

                // 按工艺分组统计数量
                // 注意：这里需要根据实际的业务逻辑来关联工艺和报工数据
                // 目前假设通过Product_id来关联，实际可能需要通过其他字段
                var reportData = productionReports
                    .GroupBy(x => x.Product_id) // 这里可能需要根据实际关联关系调整
                    .Select(g => new CraftReportQuantityDto
                    {
                        CraftId = g.Key,
                        Quantity = g.Count()
                    })
                    .ToList();

                // 如果只显示有报工记录的工艺
                if (request.OnlyWithReports)
                {
                    // 只处理有报工记录的工艺
                    var craftIds = reportData.Select(x => x.CraftId).ToList();
                    var craftsWithReports = allCrafts.Where(c => craftIds.Contains(c.Id)).ToList();

                    foreach (var report in reportData)
                    {
                        var craft = craftsWithReports.FirstOrDefault(c => c.Id == report.CraftId);
                        if (craft != null)
                        {
                            report.CraftName = craft.CraftName;
                            report.CraftCode = craft.CraftNo ?? string.Empty;
                            report.CraftDesc = craft.CraftDesc;
                        }
                    }
                }
                else
                {
                    // 显示所有工艺，包括没有报工记录的
                    foreach (var craft in allCrafts)
                    {
                        var existingReport = reportData.FirstOrDefault(r => r.CraftId == craft.Id);
                        if (existingReport == null)
                        {
                            reportData.Add(new CraftReportQuantityDto
                            {
                                CraftId = craft.Id,
                                CraftName = craft.CraftName,
                                CraftCode = craft.CraftNo ?? string.Empty,
                                CraftDesc = craft.CraftDesc,
                                Quantity = 0
                            });
                        }
                        else
                        {
                            existingReport.CraftName = craft.CraftName;
                            existingReport.CraftCode = craft.CraftNo ?? string.Empty;
                            existingReport.CraftDesc = craft.CraftDesc;
                        }
                    }
                }

                // 应用排序
                switch (request.SortType)
                {
                    case 1: // 按数量升序
                        reportData = reportData.OrderBy(x => x.Quantity).ToList();
                        break;
                    case 2: // 按数量降序
                        reportData = reportData.OrderByDescending(x => x.Quantity).ToList();
                        break;
                    case 3: // 按工艺名称
                        reportData = reportData.OrderBy(x => x.CraftName).ToList();
                        break;
                    default:
                        reportData = reportData.OrderByDescending(x => x.Quantity).ToList();
                        break;
                }

                // 构建图表数据
                chartData.CraftNames = reportData.Select(x => x.CraftName).ToList();
                chartData.Quantities = reportData.Select(x => x.Quantity).ToList();
                chartData.Details = reportData;
                chartData.TotalQuantity = reportData.Sum(x => x.Quantity);
                chartData.CraftCount = reportData.Count;

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
                result.Data = chartData;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"查询失败：{ex.Message}";
                result.Data = new CraftReportChartDto();
            }

            return result;
        }
    }
}
